import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import { Toast, Modal, } from "antd-mobile";
import { Row, Col, Card } from "antd";
import { ROUTE_PATH } from "src/projects/app/util-tool";
import './index.less';
import { AppServiceUtility } from "src/projects/app/appService";
import { request } from "src/business/util_tool";
const alert = Modal.alert;
/**
 * 组件：居家服务套餐页面视图控件状态
 */
export interface ServicePackageListViewState extends ReactViewState {
    btnState?: any;
    food_list?: any;
    modal?: any;
    list?: any;
    menu_list?: any;
    tabs?: any;
    buy_list?: any;
    price?: any;
    tab_show_list?: any;
    food_data?: any;
    visible?: any;
    buy_info?: any;
    /** 区域列表 */
    areaList?: any;
    /** 服务商列表 */
    ServiceProviderList?: any;
    areaId?: any;
}
/**
 * 组件：居家服务套餐页面视图控件
 */
export class ServicePackageListView extends ReactView<ServicePackageListViewControl, ServicePackageListViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            btnState: [],
            list: [{ 'id': 1, 'food_name': '打扫房间', 'food_detail': '...', 'tuijian': '6', 'surplus': '10', 'sell': '30', 'image': 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572521604937&di=b25d6c8984070b81e08bf353b1755dc5&imgtype=0&src=http%3A%2F%2Fpic.51yuansu.com%2Fpic3%2Fcover%2F01%2F99%2F64%2F5984bfbfa9e94_610.jpg', 'price': 50 },
            { 'id': 2, 'food_name': '清洗衣服', 'food_detail': '...', 'tuijian': '6', 'surplus': '10', 'sell': '30', 'image': 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572521639479&di=c913af65cf6bb261c50654534334d575&imgtype=0&src=http%3A%2F%2Fwww.tbw-xie.com%2FtuxieJDEwLmFsaWNkbi5jb20vaTQvMjI2MDI2MDQ0Ny9UQjJYOHFiY1BneV91SmpTWlNnWFhiejBYWGFfISEyMjYwMjYwNDQ3JDk.jpg', 'price': 100 },
            { 'id': 3, 'food_name': '剪发', 'food_detail': '...', 'tuijian': '6', 'surplus': '10', 'sell': '30', 'image': 'http://img4.imgtn.bdimg.com/it/u=2884420034,1776269664&fm=26&gp=0.jpg', 'price': 30 }],
            food_list: [],
            buy_list: [],
            modal: false,
            price: 0,
            tab_show_list: [],
            food_data: [],
            visible: false,
            buy_info: {},
            areaList: [],
            ServiceProviderList: [],
            areaId: '',
        };
    }
    areaChoose = () => {
        let list: any = [];
        this.state.areaList.map((item: any) => {
            list.push({
                text: item.name, onPress: () => {
                    console.log(item.id);
                    let areaId = item.id;
                    this.setState({
                        areaId
                    });
                    console.log(this.state.areaId);
                    this.selectServiceProvider(item.id);
                }
            });
        });
        console.log(list);
        alert('服务区域', <div>请选择你的区域</div>, list);
    }
    selectServiceProvider = (id: any) => {
        console.log(id);
        request(this, AppServiceUtility.service_operation_service.get_service_provider_list_all!({ admin_area_id: id }))
            .then((data: any) => {
                console.log("服务商信息>>>>>>>>>>>>>", data);
                let list = this.state.ServiceProviderList;
                data.result.map((item: any) => {
                    let score = 0;
                    item.qualification_info.map((item: any) => {
                        // if (item.qualification_type_id === 'cbf6fe52-d07e-11e9-8be3-144f8aec0be6') {
                        score = item.qualification_level;
                        // }
                    });
                    list.push({ id: item.id, name: item.name, score: score, remarks: '￥12', distance: '0.33km', reservation_number: '323', img_url: 'http://img3.redocn.com/tupian/20141126/xianglabazhuayu_3613154.jpg' });
                    this.setState({
                        ServiceProviderList: list
                    });
                });
            });
    }
    componentDidMount() {
        let id = this.props.match!.params.key;
        console.log(id);
        if (id === 'xfxz') {
            // 幸福院铲平
            request(this, AppServiceUtility.service_package_service.get_service_product_package_list!({ service_product_type: "福利院", }, undefined, undefined))
                .then((data: any) => {
                    console.log(data);
                    if (data.total > 0) {
                        let list: any = [];
                        data.result.map((item: any) => {
                            list.push({
                                'id': item.id,
                                'food_name': item.name,
                                'food_detail': '...',
                                'tuijian': '',
                                'surplus': '1000',
                                'sell': item.pay_count ? item.pay_count : 0,
                                'image': item.picture_collection.length > 0 ? item.picture_collection[0] : 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572521604937&di=b25d6c8984070b81e08bf353b1755dc5&imgtype=0&src=http%3A%2F%2Fpic.51yuansu.com%2Fpic3%2Fcover%2F01%2F99%2F64%2F5984bfbfa9e94_610.jpg',
                                'price': item.total_price ? item.total_price : 0
                            });
                        });
                        this.setState({
                            list
                        });
                        this.listChange();
                    }
                });
            return;
        }
        // 根据服务商id获取服务产品
        request(this, AppServiceUtility.service_package_service.get_service_product_package_list!({ service_product_type: "居家服务", org_id: id }, undefined, undefined))
            .then((data: any) => {
                console.log(data);
                if (data.total > 0) {
                    let list: any = [];
                    data.result.map((item: any) => {
                        list.push({
                            'id': item.id,
                            'food_name': item.name,
                            'food_detail': '...',
                            'tuijian': '',
                            'surplus': '1000',
                            'sell': item.pay_count ? item.pay_count : 0,
                            'image': item.picture_collection.length > 0 ? item.picture_collection[0] : 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572521604937&di=b25d6c8984070b81e08bf353b1755dc5&imgtype=0&src=http%3A%2F%2Fpic.51yuansu.com%2Fpic3%2Fcover%2F01%2F99%2F64%2F5984bfbfa9e94_610.jpg',
                            'price': item.total_price ? item.total_price : 0
                        });
                    });
                    this.setState({
                        list
                    });
                    this.listChange();
                }
            });

    }
    goPayment = (e: any) => {
        e.nativeEvent.stopImmediatePropagation();
        e.stopPropagation();
        console.log(JSON.stringify(this.state.buy_list));
        if (this.state.buy_list.length > 0) {
            let data = '';
            this.state.buy_list.forEach((item: any) => {
                data !== '' ? data = data + '___' + JSON.stringify(item) : data = JSON.stringify(item);
                console.log(data);
            });
            this.props.history!.push(ROUTE_PATH.cleanSubmitOrder + '/' + data);
        } else {
            Toast.fail('你还未选择商品！！！', 1);
        }
    }
    onClose = () => {
        this.setState({
            modal: false,
        });
    }
    showModal = (e: any) => {
        e.preventDefault(); // 修复 Android 上点击穿透
        this.setState({
            modal: true,
        });
    }
    // 添加购物车
    addFood = (id: any, name: any, price: any, food_detail: any, image: any, time: any) => {
        console.log(id + ">>>>>>>" + name);
        // 拿到食物的id
        let buy_list = this.state.buy_list;
        buy_list.push({ 'id': id, 'name': name, 'num': 1, 'price': price, 'food_detail': food_detail, 'image': encodeURIComponent(image), "time": time });
        let list = this.state.btnState;
        list.map((item: any) => {
            if (item.id === id) {
                item.state = true;
            }
        });
        let allPrice = this.state.price + price;
        this.setState({
            buy_list,
            btnState: list,
            price: allPrice,
            visible: true
        });
        Toast.success('加入购物车成功！！', 1);
        this.listChange();
        this.btnDisable(id);
    }
    // 查找按钮的状态
    btnDisable = (id: any) => {
        if (this.state.btnState.length > 0) {
            let btnState = false;
            this.state.btnState.map((item: any) => {
                if (item.id === id) {
                    return btnState = item.state;
                }
            });
            console.log(btnState);
            return btnState;
        }
        return false;
    }
    // 购物详情数量变化回调
    stepChange = (value: any, id: any, day: any, time: any, price: any, tabIndex: any) => {
        console.log(value);
        let list = this.state.buy_list;
        let btnState = this.state.btnState;
        let allPrice = 0;
        console.log("list>>>>>>>>>", list);
        list.map((item: any, index: any) => {
            if (value === 0) {
                if (item.id === id) {
                    allPrice = this.state.price - price;
                    list.splice(index, 1);
                    btnState.map((items: any) => {
                        if (items.id === id) {
                            items.state = false;
                        }
                    });
                    this.listChange();
                }
            } else {
                if (item.id === id) {
                    console.log(value);
                    // allPrice = value * price;
                    if (value >= item.num) {
                        allPrice = this.state.price + price;
                    } else {
                        allPrice = this.state.price - price;
                    }
                    item.num = value;
                    this.listChange();
                }
            }
        });

        this.setState({
            buy_list: list,
            btnState,
            price: allPrice
        });
    }
    listChange = () => {
        let food_list: any = [];
        this.state.list.map((item: any, index: any) => {
            let list = this.state.btnState;
            if (list.length > 0) {
                let idList: any = [];
                list.map((listItem: any) => {
                    idList.push(listItem.id);
                });
                if (!idList.includes(item.id)) {
                    list.push({ 'id': item.id, 'state': false });
                    this.setState({
                        btnState: list
                    });
                } else {
                    this.setState({
                        btnState: list
                    });
                }
            } else {
                list.push({ 'id': item.id, 'state': false });
                this.setState({
                    btnState: list
                });
            }
            let food = (
                <div className="clean-list" key={index} onClick={() => this.goDetails(item.id)} style={{ margin: '0px' }}>
                    <Card className='list-conten'>
                        <Row type='flex' justify='center'>
                            <Col className='list-col' span={12}><img src={item.image} style={{ height: '72pt', width: '130px' }} /></Col>
                            <Col span={12} className='list-col'>
                                <Row><strong>{item.food_name}</strong></Row>
                                <Row>
                                    <span>￥{item.price}</span>
                                    {/* <Button disabled={this.btnDisable(item.id)} type="warning" size="small" style={{ float: "right" }} onClick={(e: any) => { this.showDatePicker(e, item.id, item.food_name, item.price, item.food_detail, item.image); }}>购买</Button> */}
                                </Row>
                                {/* <Row>{item.tuijian}人推荐</Row> */}
                                <Row>
                                    <Col span={12}>剩余:{item.surplus}</Col>
                                    <Col span={12}>已售:{item.sell}</Col>
                                </Row>
                                {/* <Row>
                                    <Button disabled={this.btnDisable(item.id)} type="warning" size="small" style={{ float: "right" }} onClick={(e: any) => { this.showDatePicker(e, item.id, item.food_name, item.price, item.food_detail, item.image); }}>购买</Button>
                                </Row> */}
                            </Col>
                        </Row>
                    </Card>
                </div>
            );
            food_list.push(food);
            this.setState({
                food_list
            });
        });
    }
    // 跳转到详情页
    goDetails = (id: any) => {
        // e.nativeEvent.stopImmediatePropagation();
        // e.stopPropagation();
        this.props.history!.push(ROUTE_PATH.serviceDetails + '/' + id);
    }
    // 显示日期框
    showDatePicker = (e: any, id: any, name: any, price: any, food_detail: any, image: any) => {
        e.stopPropagation();
        let list = { id, name, price, food_detail, image };
        console.log(list);
        this.setState({
            visible: true,
            buy_info: list
        });
    }
    // 日期框确定回调
    DatePickerOK = () => {
        this.setState({
            visible: false
        });
    }
    //  日期框取消回调
    DatePickerCancel = () => {
        this.setState({
            visible: false
        });
    }
    //  日期框值改变事件
    DatePickerChange = (value: any) => {
        console.log(this.formatDate(value));
        let { id, name, price, food_detail, image } = this.state.buy_info;
        this.addFood(id, name, price, food_detail, image, this.formatDate(value));
    }
    // 处理时间
    formatDate = (date: any) => {
        const pad = (n: any) => n < 10 ? `0${n}` : n;
        const dateStr = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
        const timeStr = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
        return `${dateStr} ${timeStr}`;
    }
    render() {
        return (
            <div style={{ paddingLeft: '6px', paddingRight: '6px' }}>
                <div className="clean-list-content">
                    {this.state.food_list.length > 0 ? this.state.food_list.map((item: any) => {
                        return item;
                    }) : <div style={{ textAlign: 'center' }}>该服务商暂时没有服务产品</div>}
                </div>
                {/* <div style={{ overflow: 'hidden', backgroundColor: '#1890ff', width: '90%', height: '35px', position: 'fixed', bottom: '0px', left: '0px', borderRadius: '15px', marginLeft: '15px', marginRight: '15px' }}>
                    <div style={{ float: 'left', width: '50%', textAlign: 'center', lineHeight: '35px' }} onClick={this.showModal}>选购详情</div>
                    <div style={{ float: 'right', width: '30%', textAlign: 'center', lineHeight: '35px', borderLeft: "1px solid rgb(14, 12, 12)" }} onClick={this.goPayment}>确认订单</div>
                </div> */}
                {/* <Modal
                    popup={true}
                    visible={this.state.modal}
                    onClose={this.onClose}
                    animationType="slide-up"
                    style={{ overflow: 'scroll', height: '300px' }}
                >
                    <List renderHeader={() => <div>选购详情</div>} style={{ overflow: 'scroll' }}>
                        {this.state.buy_list.map((item: any) => (
                            <List.Item key={item.id} style={{ overflow: 'scroll' }}>{item.name}<Stepper key={item.id} value={item.num} showNumber={true} max={10} min={0} onChange={(value) => { this.stepChange(value, item.id, item.day, item.time, item.price, item.index); }} /></List.Item>
                        ))}
                        <List.Item>
                            <Button type="primary" onClick={this.onClose} style={{ position: 'fixed', bottom: '0px', width: '100%', left: '0px' }}>￥{this.state.price}</Button>
                        </List.Item>
                    </List>
                </Modal> */}
                {/* <DatePicker
                    visible={this.state.visible}
                    onOk={this.DatePickerOK}
                    onDismiss={this.DatePickerCancel}
                    onChange={(value: any) => { this.DatePickerChange(value); }}
                    title="请选择服务时间"
                /> */}
            </div>
        );
    }
}

/**
 * 组件：居家服务套餐页面视图控件
 * 控制居家服务套餐页面视图控件
 */
@addon('ServicePackageListView', '居家服务套餐页面视图控件', '控制居家服务套餐页面视图控件')
@reactControl(ServicePackageListView, true)
export class ServicePackageListViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}